package com.example.threaddemo;

import java.util.concurrent.TimeUnit;

class LockSource implements Runnable {
    public String lockA;
    public String lockB;


    public LockSource(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "\t  正在持有" + lockA + ";尝试持有" + lockB);
            try {
                TimeUnit.SECONDS.sleep(1L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t  正在持有" + lockB + ";尝试持有" + lockA);
            }
        }
    }
}

/**
 * 互相持有的死锁
 * 排查：1. 查看当前运行的线程列表   jps -l
 *      2. 查看具体的线程信息       jstack 999
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new LockSource(lockA, lockB), "A").start();
        new Thread(new LockSource(lockB, lockA), "B").start();
    }
}
